<template>
  <div class="queue-list-container">
    <div class="page-header">
      <h2 class="page-title">队列列表</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleCreateQueue">
          <el-icon><Plus /></el-icon>新建队列
        </el-button>
        <el-button @click="handleRefresh">
          <el-icon><Refresh /></el-icon>刷新
        </el-button>
      </div>
    </div>
    
    <!-- 搜索过滤器 -->
    <div class="filter-container">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="队列名称">
          <el-input v-model="filterForm.queueName" placeholder="请输入队列名称" clearable />
        </el-form-item>
        <el-form-item label="业务类型">
          <el-select v-model="filterForm.businessTypeId" placeholder="请选择业务类型" clearable>
            <el-option
              v-for="item in businessTypes"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filterForm.status" placeholder="请选择状态" clearable>
            <el-option label="开放" value="OPEN" />
            <el-option label="关闭" value="CLOSED" />
            <el-option label="暂停" value="PAUSED" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 队列表格 -->
    <div class="queue-table">
      <el-table
        :data="queueList"
        style="width: 100%"
        v-loading="tableLoading"
        border
      >
        <el-table-column type="index" width="50" />
        <el-table-column prop="queueName" label="队列名称" min-width="120" />
        <el-table-column prop="businessType" label="业务类型" min-width="120" />
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="waitingCount" label="等待人数" width="100" sortable />
        <el-table-column prop="processingCount" label="处理中人数" width="120" sortable />
        <el-table-column prop="completedCount" label="今日完成数" width="120" sortable />
        <el-table-column prop="avgWaitTime" label="平均等待时间" width="140">
          <template #default="scope">
            {{ formatTime(scope.row.avgWaitTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220">
          <template #default="scope">
            <el-button size="small" @click="handleViewQueue(scope.row)">详情</el-button>
            <el-button size="small" type="primary" @click="handleEditQueue(scope.row)">编辑</el-button>
            <el-button 
              size="small" 
              :type="scope.row.status === 'OPEN' ? 'warning' : 'success'"
              @click="handleToggleStatus(scope.row)"
            >
              {{ scope.row.status === 'OPEN' ? '暂停' : '开放' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:currentPage="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    
    <!-- 新建/编辑队列对话框 -->
    <el-dialog
      v-model="queueDialog.visible"
      :title="queueDialog.isEdit ? '编辑队列' : '新建队列'"
      width="600px"
    >
      <el-form
        ref="queueFormRef"
        :model="queueForm"
        :rules="queueRules"
        label-width="100px"
      >
        <el-form-item label="队列名称" prop="queueName">
          <el-input v-model="queueForm.queueName" placeholder="请输入队列名称" />
        </el-form-item>
        <el-form-item label="业务类型" prop="businessTypeId">
          <el-select v-model="queueForm.businessTypeId" placeholder="请选择业务类型" style="width: 100%">
            <el-option
              v-for="item in businessTypes"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="队列前缀" prop="prefix">
          <el-input v-model="queueForm.prefix" placeholder="请输入排队号码前缀，如A、B等" maxlength="3" />
        </el-form-item>
        <el-form-item label="当前序号" prop="currentNumber">
          <el-input-number v-model="queueForm.currentNumber" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="最大容量" prop="maxCapacity">
          <el-input-number 
            v-model="queueForm.maxCapacity" 
            :min="10" 
            :max="1000" 
            placeholder="最大排队人数" 
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queueForm.status" placeholder="请选择状态" style="width: 100%">
            <el-option label="开放" value="OPEN" />
            <el-option label="关闭" value="CLOSED" />
            <el-option label="暂停" value="PAUSED" />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="queueForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入队列描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="queueDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="submitQueueForm">确定</el-button>
      </template>
    </el-dialog>
    
    <!-- 队列详情对话框 -->
    <el-dialog
      v-model="queueDetail.visible"
      title="队列详情"
      width="800px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="队列名称">{{ queueDetail.data.queueName }}</el-descriptions-item>
        <el-descriptions-item label="业务类型">{{ queueDetail.data.businessType }}</el-descriptions-item>
        <el-descriptions-item label="队列前缀">{{ queueDetail.data.prefix }}</el-descriptions-item>
        <el-descriptions-item label="当前序号">{{ queueDetail.data.currentNumber }}</el-descriptions-item>
        <el-descriptions-item label="最大容量">{{ queueDetail.data.maxCapacity }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(queueDetail.data.status)">
            {{ getStatusText(queueDetail.data.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间" :span="2">{{ queueDetail.data.createTime }}</el-descriptions-item>
        <el-descriptions-item label="描述" :span="2">{{ queueDetail.data.description }}</el-descriptions-item>
      </el-descriptions>
      
      <div class="queue-stats" v-if="queueDetail.stats">
        <h3>当前统计数据</h3>
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="stat-card">
              <div class="stat-value">{{ queueDetail.stats.waitingCount }}</div>
              <div class="stat-label">等待人数</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="stat-card">
              <div class="stat-value">{{ queueDetail.stats.processingCount }}</div>
              <div class="stat-label">处理中人数</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="stat-card">
              <div class="stat-value">{{ queueDetail.stats.completedCount }}</div>
              <div class="stat-label">今日完成数</div>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20" style="margin-top: 15px;">
          <el-col :span="8">
            <div class="stat-card">
              <div class="stat-value">{{ formatTime(queueDetail.stats.avgWaitTime) }}</div>
              <div class="stat-label">平均等待时间</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="stat-card">
              <div class="stat-value">{{ formatTime(queueDetail.stats.avgServiceTime) }}</div>
              <div class="stat-label">平均服务时间</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="stat-card">
              <div class="stat-value">{{ queueDetail.stats.skippedCount }}</div>
              <div class="stat-label">跳过数量</div>
            </div>
          </el-col>
        </el-row>
      </div>
      
      <template #footer>
        <el-button @click="queueDetail.visible = false">关闭</el-button>
        <el-button type="primary" @click="handleEditQueue(queueDetail.data)">编辑</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh, Search } from '@element-plus/icons-vue'

export default {
  name: 'QueueList',
  components: {
    Plus,
    Refresh,
    Search
  },
  setup() {
    // 队列列表数据
    const queueList = ref([])
    const tableLoading = ref(false)
    
    // 业务类型列表
    const businessTypes = ref([])
    
    // 分页信息
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0
    })
    
    // 过滤表单
    const filterForm = reactive({
      queueName: '',
      businessTypeId: '',
      status: ''
    })
    
    // 队列对话框
    const queueDialog = reactive({
      visible: false,
      isEdit: false
    })
    
    // 队列表单
    const queueFormRef = ref(null)
    const queueForm = reactive({
      id: null,
      queueName: '',
      businessTypeId: '',
      prefix: '',
      currentNumber: 0,
      maxCapacity: 100,
      status: 'OPEN',
      description: ''
    })
    
    // 表单验证规则
    const queueRules = {
      queueName: [
        { required: true, message: '请输入队列名称', trigger: 'blur' },
        { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
      ],
      businessTypeId: [
        { required: true, message: '请选择业务类型', trigger: 'change' }
      ],
      prefix: [
        { required: true, message: '请输入队列前缀', trigger: 'blur' },
        { pattern: /^[A-Za-z]{1,3}$/, message: '前缀只能是1-3个字母', trigger: 'blur' }
      ],
      status: [
        { required: true, message: '请选择状态', trigger: 'change' }
      ]
    }
    
    // 队列详情
    const queueDetail = reactive({
      visible: false,
      data: {
        id: null,
        queueName: '',
        businessType: '',
        prefix: '',
        currentNumber: 0,
        maxCapacity: 0,
        status: '',
        createTime: '',
        description: ''
      },
      stats: null
    })
    
    // 格式化等待时间
    const formatTime = (seconds) => {
      if (!seconds || seconds <= 0) return '0分钟'
      
      const minutes = Math.floor(seconds / 60)
      const remainingSeconds = Math.floor(seconds % 60)
      
      if (minutes === 0) {
        return `${remainingSeconds}秒`
      } else if (remainingSeconds === 0) {
        return `${minutes}分钟`
      } else {
        return `${minutes}分钟${remainingSeconds}秒`
      }
    }
    
    // 获取状态类型
    const getStatusType = (status) => {
      switch (status) {
        case 'OPEN': return 'success'
        case 'CLOSED': return 'danger'
        case 'PAUSED': return 'warning'
        default: return 'info'
      }
    }
    
    // 获取状态文本
    const getStatusText = (status) => {
      switch (status) {
        case 'OPEN': return '开放'
        case 'CLOSED': return '关闭'
        case 'PAUSED': return '暂停'
        default: return '未知'
      }
    }
    
    // 获取队列列表
    const fetchQueueList = () => {
      tableLoading.value = true
      
      setTimeout(() => {
        // 模拟API返回数据
        const mockQueueData = [
          {
            id: 1,
            queueName: '个人业务办理',
            businessTypeId: 1,
            businessType: '个人业务',
            prefix: 'A',
            currentNumber: 125,
            maxCapacity: 200,
            waitingCount: 15,
            processingCount: 3,
            completedCount: 108,
            avgWaitTime: 480, // 8分钟
            description: '个人业务办理队列，包括个人账户开户、变更等业务',
            status: 'OPEN',
            createTime: '2023-06-01 08:00:00'
          },
          {
            id: 2,
            queueName: '对公业务办理',
            businessTypeId: 2,
            businessType: '对公业务',
            prefix: 'B',
            currentNumber: 35,
            maxCapacity: 100,
            waitingCount: 8,
            processingCount: 2,
            completedCount: 25,
            avgWaitTime: 780, // 13分钟
            description: '对公业务办理队列，包括企业账户开户、变更等业务',
            status: 'OPEN',
            createTime: '2023-06-01 08:00:00'
          },
          {
            id: 3,
            queueName: '社保业务办理',
            businessTypeId: 3,
            businessType: '社保业务',
            prefix: 'C',
            currentNumber: 42,
            maxCapacity: 150,
            waitingCount: 10,
            processingCount: 1,
            completedCount: 31,
            avgWaitTime: 540, // 9分钟
            description: '社保业务办理队列，包括社保卡办理、社保缴费等业务',
            status: 'OPEN',
            createTime: '2023-06-01 08:00:00'
          },
          {
            id: 4,
            queueName: '综合查询',
            businessTypeId: 4,
            businessType: '咨询查询',
            prefix: 'D',
            currentNumber: 56,
            maxCapacity: 120,
            waitingCount: 5,
            processingCount: 1,
            completedCount: 50,
            avgWaitTime: 300, // 5分钟
            description: '综合查询业务，包括业务咨询、信息查询等',
            status: 'PAUSED',
            createTime: '2023-06-01 08:00:00'
          },
          {
            id: 5,
            queueName: 'VIP客户服务',
            businessTypeId: 5,
            businessType: 'VIP服务',
            prefix: 'V',
            currentNumber: 12,
            maxCapacity: 50,
            waitingCount: 2,
            processingCount: 1,
            completedCount: 9,
            avgWaitTime: 360, // 6分钟
            description: 'VIP客户专属服务队列，提供一对一专属服务',
            status: 'OPEN',
            createTime: '2023-06-01 08:00:00'
          }
        ]
        
        // 应用过滤条件
        let filteredQueues = mockQueueData.filter(queue => {
          if (filterForm.queueName && !queue.queueName.includes(filterForm.queueName)) {
            return false
          }
          if (filterForm.businessTypeId && queue.businessTypeId !== filterForm.businessTypeId) {
            return false
          }
          if (filterForm.status && queue.status !== filterForm.status) {
            return false
          }
          return true
        })
        
        // 更新分页数据
        queueList.value = filteredQueues
        pagination.total = filteredQueues.length
        
        tableLoading.value = false
      }, 500)
    }
    
    // 获取业务类型列表
    const fetchBusinessTypes = () => {
      // 模拟业务类型数据
      businessTypes.value = [
        { id: 1, name: '个人业务', code: 'PERSONAL' },
        { id: 2, name: '对公业务', code: 'CORPORATE' },
        { id: 3, name: '社保业务', code: 'SOCIAL_SECURITY' },
        { id: 4, name: '咨询查询', code: 'INQUIRY' },
        { id: 5, name: 'VIP服务', code: 'VIP' }
      ]
    }
    
    // 处理搜索
    const handleSearch = () => {
      pagination.currentPage = 1
      fetchQueueList()
    }
    
    // 重置过滤器
    const resetFilter = () => {
      Object.keys(filterForm).forEach(key => {
        filterForm[key] = ''
      })
      handleSearch()
    }
    
    // 处理页面大小变化
    const handleSizeChange = (size) => {
      pagination.pageSize = size
      fetchQueueList()
    }
    
    // 处理页码变化
    const handleCurrentChange = (page) => {
      pagination.currentPage = page
      fetchQueueList()
    }
    
    // 处理刷新
    const handleRefresh = () => {
      fetchQueueList()
    }
    
    // 处理新建队列
    const handleCreateQueue = () => {
      queueDialog.isEdit = false
      queueDialog.visible = true
      
      Object.keys(queueForm).forEach(key => {
        if (key === 'status') {
          queueForm[key] = 'OPEN'
        } else if (key === 'maxCapacity') {
          queueForm[key] = 100
        } else if (key === 'currentNumber') {
          queueForm[key] = 0
        } else {
          queueForm[key] = ''
        }
      })
    }
    
    // 处理编辑队列
    const handleEditQueue = (row) => {
      queueDialog.isEdit = true
      queueDialog.visible = true
      queueDetail.visible = false
      
      queueForm.id = row.id
      queueForm.queueName = row.queueName
      queueForm.businessTypeId = row.businessTypeId
      queueForm.prefix = row.prefix
      queueForm.currentNumber = row.currentNumber
      queueForm.maxCapacity = row.maxCapacity
      queueForm.status = row.status
      queueForm.description = row.description
    }
    
    // 处理查看队列详情
    const handleViewQueue = (row) => {
      queueDetail.visible = true
      queueDetail.data = {...row}
      
      // 模拟队列统计数据
      queueDetail.stats = {
        waitingCount: row.waitingCount,
        processingCount: row.processingCount,
        completedCount: row.completedCount,
        avgWaitTime: row.avgWaitTime,
        avgServiceTime: Math.floor(row.avgWaitTime * 0.7), // 模拟服务时间
        skippedCount: Math.floor(row.completedCount * 0.05) // 模拟跳过数量
      }
    }
    
    // 处理切换队列状态
    const handleToggleStatus = (row) => {
      const newStatus = row.status === 'OPEN' ? 'PAUSED' : 'OPEN'
      const statusText = newStatus === 'OPEN' ? '开放' : '暂停'
      
      ElMessageBox.confirm(`确定要${statusText}该队列吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 直接在前端更新状态
        const index = queueList.value.findIndex(q => q.id === row.id)
        if (index !== -1) {
          queueList.value[index].status = newStatus
          ElMessage.success(`队列${statusText}成功`)
        }
      }).catch(() => {})
    }
    
    // 提交队列表单
    const submitQueueForm = () => {
      queueFormRef.value.validate((valid) => {
        if (valid) {
          const isEdit = queueDialog.isEdit
          
          if (isEdit) {
            // 编辑现有队列
            const index = queueList.value.findIndex(item => item.id === queueForm.id)
            if (index !== -1) {
              // 获取业务类型名称
              const businessType = businessTypes.value.find(type => type.id === queueForm.businessTypeId)
              const businessTypeName = businessType ? businessType.name : ''
              
              queueList.value[index] = {
                ...queueList.value[index],
                queueName: queueForm.queueName,
                businessTypeId: queueForm.businessTypeId,
                businessType: businessTypeName,
                prefix: queueForm.prefix,
                currentNumber: queueForm.currentNumber,
                maxCapacity: queueForm.maxCapacity,
                status: queueForm.status,
                description: queueForm.description
              }
              
              ElMessage.success('队列更新成功')
              queueDialog.visible = false
            }
          } else {
            // 创建新队列
            const businessType = businessTypes.value.find(type => type.id === queueForm.businessTypeId)
            const businessTypeName = businessType ? businessType.name : ''
            
            const newId = Math.max(...queueList.value.map(item => item.id), 0) + 1
            const now = new Date().toISOString().replace('T', ' ').substring(0, 19)
            
            queueList.value.push({
              id: newId,
              queueName: queueForm.queueName,
              businessTypeId: queueForm.businessTypeId,
              businessType: businessTypeName,
              prefix: queueForm.prefix,
              currentNumber: queueForm.currentNumber,
              maxCapacity: queueForm.maxCapacity,
              waitingCount: 0,
              processingCount: 0,
              completedCount: 0,
              avgWaitTime: 0,
              description: queueForm.description,
              status: queueForm.status,
              createTime: now
            })
            
            pagination.total = queueList.value.length
            ElMessage.success('队列创建成功')
            queueDialog.visible = false
          }
        }
      })
    }
    
    onMounted(() => {
      fetchQueueList()
      fetchBusinessTypes()
    })
    
    return {
      queueList,
      tableLoading,
      businessTypes,
      pagination,
      filterForm,
      queueDialog,
      queueFormRef,
      queueForm,
      queueRules,
      queueDetail,
      formatTime,
      getStatusType,
      getStatusText,
      handleSearch,
      resetFilter,
      handleSizeChange,
      handleCurrentChange,
      handleRefresh,
      handleCreateQueue,
      handleEditQueue,
      handleViewQueue,
      handleToggleStatus,
      submitQueueForm
    }
  }
}
</script>

<style scoped>
.queue-list-container {
  padding: 15px 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 22px;
  font-weight: 500;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.filter-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.04);
}

.queue-table {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.04);
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.queue-stats {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.queue-stats h3 {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 15px;
}

.stat-card {
  background-color: #f5f7fa;
  border-radius: 4px;
  padding: 15px;
  text-align: center;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}
</style> 